package com.cxria.pattern.commandAndResponsibilityChain

class ClassUtils {

    static List<Class> getSonClass(Class<? extends CommandName> fatherClass) {
        def returnClassList = []
        String packageName = fatherClass.getPackage().name
        def packClasses = getClasses(packageName)
        for(c in packClasses){
            if(fatherClass.isAssignableFrom(c) && fatherClass != c){
                returnClassList.add(c)
            }
        }
        returnClassList
    }

    static List<Class> getClasses(String packageName) {
        ClassLoader classLoader = Thread.currentThread().contextClassLoader
        String path = packageName.replace('.', '/')
        Enumeration<URL> resources = classLoader.getResources(path)
        def dirs = []
        while(resources.hasMoreElements()){
            URL resource = resources.nextElement()
            dirs.add(new File(resource.file))
        }
        def classes = []
        for(directory in dirs){
            classes.addAll(findClasses(directory, packageName))
        }
        classes
    }

    static List<Class> findClasses(File directory, String packageName) {
        def classes = []
        if(!directory.exists()){
            return classes
        }
        File[] files = directory.listFiles()
        for(file in files){
            if(file.isDirectory()){
                assert !file.name.contains('.')
                classes.addAll(findClasses(file, "${packageName}.${file.name}"))
            } else if(file.name.endsWith('.class')){
                classes.add(Class.forName("${packageName}.${file.name.substring(0, file.name.length() - 6)}"))
            }
        }
        classes
    }

}
